<script setup>
import { updateUserPasswordAPI } from '@/api/user';
import { useTokenStore } from '@/stores/token';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const tokenStore = useTokenStore();
const userStore = useUserStore();

const passwordInfo = ref({
  oldPassword: '',
  newPassword: '',
  rePassword: '',
});

const rules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { pattern: /^\S{5,16}$/, message: '密码必须是2-10位的非空字符串', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { pattern: /^\S{5,16}$/, message: '密码必须是2-10位的非空字符串', trigger: 'blur' }
  ],
  rePassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (value !== passwordInfo.value.newPassword) {
          callback(new Error('请输入相同的新密码'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ]
};

const updateUserPassword = async () => {
  const res = await updateUserPasswordAPI(passwordInfo.value);
  ElMessage.success(res.msg || '修改成功，请重新登录');
  tokenStore.removeToken();
  userStore.removeInfo();
  router.push('/login');
};
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>重置密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form :model="passwordInfo" :rules="rules" label-width="100px" size="large">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="passwordInfo.oldPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordInfo.newPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="确认新密码" prop="rePassword">
            <el-input v-model="passwordInfo.rePassword" type="password" show-password />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateUserPassword">提交修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>